#!/usr/bin/python3.6
import sys
import os
from datetime import datetime, timezone, timedelta
from pathlib import Path
import time
import uuid

import icalendar
import typer
from zhdate import ZhDate


import contextlib
import bz2
import gzip
import io


sys.path.append(sys.path[0])
from SlurpFile import (SlurpFileZipOkay, pCON, GetRndStr, YWRand, YWRHex, Dump2Json, LoadJson, runtime, WriteZB)
#from SlurpFile import pConM as p
from SlurpFile import pConM 

app = typer.Typer()

def create_new_event(
    start: datetime,
    end: datetime,
    event_name: str,
    description: str,
) -> icalendar.Event:
  '''Create a new 'subcomponent' for icalendar.'''# <<<
  event: icalendar.Event = icalendar.Event()
  uid: str = str(uuid.uuid1())
  event.add('transp', 'TRANSPARENT')
  event.add('summary', event_name)
  event.add('description', description)
  event.add('uid', uid)
  event['dtstart'] = start
  event['dtend'] = end
  return event# >>>

@app.command()
def main(
    year: int = 2020,        # 
    occ: int = 3,            # 
    Sum: str = "农历",       # 
    desc: str = "",          # 
    lmon: str = "1",         # 
    ldy: str = "1",          # expecting format like 1,5,15
    hour: int = 2,           # 
    min: int = 22):          # 
  """
  """  # <<<
  cal1397: icalendar.Calendar = icalendar.Calendar()

  utc_diff_sec = time.timezone  # time difference from utc, in seconds
  del2717 = timedelta(seconds=utc_diff_sec)
  del2959 = timedelta(minutes=min)              # the addition into minutes
  del4693 = timedelta(hours=hour)               # the addition into hour
  del3545 = timedelta(minutes=5)                # the duration; determines dtend

  end_year = year + occ
  ldays = [int(d1599) for d1599 in ldy.split(",")]
  lmons = [int(d1600) for d1600 in lmon.split(",")]

  for y1 in range(year, end_year):
    for lnM in lmons:
      for lnD in ldays:
        try:  # if raise error, likely due to lnD==30 for a 29-day month
          ld3176 = ZhDate(y1, lnM, lnD)  #
        except TypeError as e:
          lnD -= 1
          ld3176 = ZhDate(y1, lnM, lnD)
        else:
          pass
        d1754 = ld3176.to_datetime()
        #      print(f"### {{{__file__}}}---{{{sys._getframe().f_lineno:>4}}}--{type(d1754)}-{d1754}", flush=True)
        d7106 = d1754 + del2717 + del2959 + del4693  # adding hour, min and diff-to-utc
        d6970 = d7106 + del3545  # adding 5-min slot
        st2116 = d7106.strftime('%Y%m%dT%H%M%S') + "Z"
        st2117 = d6970.strftime('%Y%m%dT%H%M%S') + "Z"
        ev7832: icalendar.Event = create_new_event(st2116, st2117, Sum, f"{ld3176} {desc}")
        cal1397.add_component(ev7832)

  st = YWRHex()
  WriteZB(f"{st}.ics", cal1397.to_ical())


#   calt = cal1397.to_ical().decode('utf-8')
#   pConM(calt)

# >>>

if __name__ == "__main__":
  app() # Typer suggests to call the decorator
